using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace GenerateP4SpecForm
{
    public static class SpecWriter
    {
        public static void WriteP4SpecForm(string outputPath, string[] options)
        {
            StringBuilder specBuilder = new StringBuilder();
            foreach (string option in options)
            {
                specBuilder.AppendLine(option);
            }
            File.WriteAllText(outputPath, specBuilder.ToString());
        }

        public static void UpdateP4SpecForm(string path, string searchString, string replaceString)
        {
            string contents = File.ReadAllText(path);
            contents = contents.Replace(searchString, replaceString);
            File.WriteAllText(path, contents);
        }

        public static void AppendToP4SpecForm(string path, string additionalString)
        {
            //check the string is not already present:
            string contents = File.ReadAllText(path);
            if (!contents.Contains(additionalString))
            {
                //NOTE - P4 is fussy about its spec file formatting; we need to remove
                //all the NewLines at the end, then add a tab, then the new string, then
                //a NewLine. Specifically for adding views to the end of client specs:
                contents = contents.TrimEnd(Environment.NewLine.ToCharArray());
                contents = string.Format("{0}{1}\t{2}{1}", contents, Environment.NewLine, additionalString);
                File.WriteAllText(path, contents);
            }
        }
    }
}
